package com.example.checkqufuface.View.QufuKaProject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.example.checkqufuface.Base.BaseActivity;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.SPUtils;
import com.example.checkqufuface.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.ThreadManager;
import com.example.baselibrary.Utils.ToastUtil;
import com.example.checkqufuface.Customer.SettingDialog;
import com.example.checkqufuface.R;
import com.example.checkqufuface.RetrufitHelp.BaseSubscriber;
import com.example.checkqufuface.RetrufitHelp.ExceptionHandle;
import com.example.checkqufuface.RetrufitHelp.RetrofitClient;
import com.example.checkqufuface.Utils.GetDeviceId;
import com.example.checkqufuface.bean.QufuLoginRequestBean;
import com.example.checkqufuface.bean.QufuLoginResultBean;

public class LoginKaActivity extends BaseActivity {

    private EditText etAccount;
    private EditText etPassword;
    private Button btLogin;
    private CheckBox cbName;
    private String DeviceId;
    private QufuLoginRequestBean loginRequestBean;

    private TextView ipSet;
    private SettingDialog settingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getView() {
        return R.layout.activity_login_ka;
    }

    @Override
    public void init() {
        //获取设备码
        getDeviceId();

        ipSet = findViewById(R.id.tv_set_ip);

        if (loginRequestBean == null) {
            loginRequestBean = new QufuLoginRequestBean();
        }

        etAccount = findViewById(R.id.et_login_account);
        etPassword = findViewById(R.id.et_login_password);
        btLogin = findViewById(R.id.bt_login_in);
        cbName = findViewById(R.id.login_save_name_password);

        prepareThing();
        initData();
    }

    private void prepareThing() {

        etAccount.setText((String) SPUtils.get(LoginKaActivity.this, Customer.QUFU_LOGIN_ACCOUNT, ""));
        etPassword.setText((String) SPUtils.get(LoginKaActivity.this, Customer.QUFU_LOGIN_PASSWORD, ""));

        //是否记住密码
        boolean isRember = (boolean) SPUtils.get(LoginKaActivity.this, Customer.QUFU_IS_REMBER, false);
        if (isRember) {
            cbName.setChecked(true);
        }else {
            cbName.setChecked(false);
        }
    }

    private void initData() {

        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAndLogin();
            }
        });

        ipSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ipSetting();
            }
        });
    }


    private void ipSetting() {
        if (settingDialog == null) {
            settingDialog = new SettingDialog(LoginKaActivity.this).builder()
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            settingDialog.getDialog().dismiss();
                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String inPut = settingDialog.getInPut();
                            if (inPut.isEmpty()) {
                                ToastUtil.showToast("请输入Ip");
                            } else {
                                // 保存数据
                                BASE_URL = inPut;
                                SPUtils.put(LoginKaActivity.this, Customer.QUFU_INPUT_URL, true);
                                SPUtils.put(LoginKaActivity.this, Customer.QUFU_INPUT_URL, inPut);
                                settingDialog.getDialog().dismiss();
                                SelfToastUtil.getInstance().show("地址保存成功");
                            }
                        }
                    });
        }

        settingDialog.show();
    }
    //内部方法 写在 下面
    private void checkAndLogin() {
        String account = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (StringUtil.isNullOrEmpty(account) || StringUtil.isNullOrEmpty(password)) {
            //如果有一个为空，那么就提示
            ToastUtil.showToast("用户名或密码为空，请先确认");
            return;
        }
        // 如果两个参数不为空，那么就去登入
        goToLogin(account, password);


    }

    private void goToLogin(final String account, final String password) {
        loginRequestBean.setUserName(account);
        loginRequestBean.setPassword(password);
        loginRequestBean.setLoginType("3");
        loginRequestBean.setTerminalComputerCpuId(DeviceId);
        RetrofitClient.getInstance(LoginKaActivity.this,BASE_URL).QuFulogin(loginRequestBean, new BaseSubscriber<QufuLoginResultBean>(LoginKaActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuLoginResultBean qufuLoginResultBean) {
                String code = qufuLoginResultBean.getCode();
                if (code.equals("200")) {

                    if (cbName.isChecked()) {
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_LOGIN_ACCOUNT, account);
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_LOGIN_PASSWORD, password);
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_IS_REMBER, true);
                    } else {
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_LOGIN_ACCOUNT, "");
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_LOGIN_PASSWORD, "");
                        SPUtils.put(LoginKaActivity.this, Customer.QUFU_IS_REMBER, false);
                    }
                    SPUtils.put(LoginKaActivity.this, Customer.QUFU_ACCESSTOKEN, qufuLoginResultBean.getData().getUserInfo().getAccessToken());
                    SPUtils.put(LoginKaActivity.this, Customer.QUFU_REFRESHTOKEN, qufuLoginResultBean.getData().getUserInfo().getRefreshToken());

                    //数据保存完成，然后去登入
                    startActivity(new Intent(LoginKaActivity.this, QufuKaHomeActivity.class));
                }else {
                    SelfToastUtil.getInstance().show(qufuLoginResultBean.getMessage());
                }
            }
        });
    }

    private void getDeviceId() {

        //获取设备唯一标识
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    DeviceId = GetDeviceId.getDeviceId(LoginKaActivity.this);
                    //获取保存在sd中的 设备唯一标识符
                    String readDeviceID = GetDeviceId.readDeviceID(LoginKaActivity.this);
                    //获取缓存在  sharepreference 里面的 设备唯一标识
                    String string = (String) SPUtils.get(LoginKaActivity.this, Customer.QUFU_DEVICE_ID, "");
                    //判断 app 内部是否已经缓存,  若已经缓存则使用app 缓存的 设备id
                    if (string != null && !string.equals("")) {
                        // 说明有保存，那么久将其放出去呗
                        if (readDeviceID.equals(string)) {
                            //缓存和文件地址一样，直接返回出去
                            DeviceId = readDeviceID;
                        }
                    } else {
                        DeviceId = GetDeviceId.getDeviceId(LoginKaActivity.this);
                        GetDeviceId.saveDeviceID(DeviceId, LoginKaActivity.this);
                    }
                    //最后再次更新app 的缓存
                    SPUtils.put(LoginKaActivity.this, Customer.QUFU_DEVICE_ID, DeviceId);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
